<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.domain.Post, com.example.domain.PageResult, com.example.domain.Category, com.example.domain.User" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>论坛首页</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);
            min-height: 100vh;
            color: #374151;
        }

        .header {
            background: white;
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid #e2e8f0;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 16px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .logo {
            font-size: 28px;
            font-weight: bold;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .user-nav {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .user-nav a {
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }

        .user-nav a:hover {
            transform: translateY(-2px);
        }

        .nav-primary {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white !important;
        }

        .nav-primary:hover {
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.4);
        }

        .nav-secondary {
            border-color: #e5e7eb;
            color: #374151 !important;
        }

        .nav-secondary:hover {
            background: #f9fafb;
            border-color: #d1d5db;
        }

        .nav-ghost {
            color: #6b7280 !important;
        }

        .nav-ghost:hover {
            background: #f3f4f6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 32px 20px;
        }

        .page-title {
            text-align: center;
            margin-bottom: 40px;
        }

        .page-title h1 {
            font-size: 36px;
            font-weight: bold;
            background: linear-gradient(135deg, #1f2937 0%, #3b82f6 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 8px;
        }

        .search-section {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 32px;
            overflow: hidden;
        }

        .search-header {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            padding: 20px 24px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .search-header h3 {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }

        .search-form {
            padding: 24px;
        }

        .form-row {
            display: flex;
            gap: 16px;
            align-items: end;
            flex-wrap: wrap;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        .form-group select,
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-group select:focus,
        .form-group input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .search-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 12px 24px;
            border-radius: 25px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        }

        .btn-outline {
            background: transparent;
            border: 2px solid #e5e7eb;
            color: #374151;
        }

        .btn-outline:hover {
            background: #f9fafb;
            border-color: #d1d5db;
            transform: translateY(-2px);
        }

        .posts-grid {
            display: grid;
            gap: 24px;
        }

        .post-item {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            overflow: hidden;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .post-item:hover {
            transform: translateY(-8px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .post-content {
            padding: 24px;
        }

        .post-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 16px;
            gap: 16px;
        }

        .post-title {
            flex: 1;
        }

        .post-title h3 {
            margin: 0 0 12px 0;
            font-size: 20px;
            font-weight: 600;
            line-height: 1.4;
        }

        .post-title a {
            color: #1f2937;
            text-decoration: none;
            transition: color 0.3s ease;
        }

        .post-title a:hover {
            color: #3b82f6;
        }

        .post-meta {
            display: flex;
            align-items: center;
            gap: 16px;
            color: #6b7280;
            font-size: 14px;
            flex-wrap: wrap;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .post-text {
            color: #4b5563;
            line-height: 1.6;
            margin-bottom: 20px;
        }

        .post-actions {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 16px;
        }

        .action-buttons {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .like-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: 20px;
            border: 2px solid #f472b6;
            background: transparent;
            color: #f472b6;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .like-btn.liked {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
        }

        .like-btn:hover {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
            transform: translateY(-2px);
        }

        .action-link {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .link-primary {
            border: 2px solid #3b82f6;
            color: #3b82f6;
        }

        .link-primary:hover {
            background: #3b82f6;
            color: white;
            transform: translateY(-2px);
        }

        .link-success {
            border: 2px solid #10b981;
            color: #10b981;
        }

        .link-success:hover {
            background: #10b981;
            color: white;
            transform: translateY(-2px);
        }

        .like-display {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #6b7280;
            font-size: 14px;
        }

        .pagination-section {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 24px;
            margin-top: 32px;
        }

        .pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 16px;
        }

        .pagination-buttons {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .page-link {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 8px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid #e5e7eb;
            color: #374151;
            background: white;
            min-width: 40px;
        }

        .page-link:hover {
            background: #f3f4f6;
            transform: translateY(-1px);
        }

        .page-link.current {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            border-color: transparent;
        }

        .pagination-info {
            color: #6b7280;
            font-size: 14px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6b7280;
        }

        .empty-state h3 {
            font-size: 24px;
            margin-bottom: 12px;
            color: #374151;
        }

        .message-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 10px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }

        .message-toast.show {
            transform: translateX(0);
        }

        .message-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }

        .message-error {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }

            .form-row {
                flex-direction: column;
            }

            .form-group {
                min-width: auto;
            }

            .search-buttons {
                width: 100%;
                justify-content: center;
            }

            .post-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .post-actions {
                flex-direction: column;
                align-items: flex-start;
            }

            .pagination {
                flex-direction: column;
                text-align: center;
            }

            .pagination-buttons {
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 20px 16px;
            }

            .post-content {
                padding: 20px;
            }

            .search-form {
                padding: 20px;
            }

            .action-buttons {
                width: 100%;
                justify-content: space-between;
            }
        }
    </style>
</head>
<body>
<%
    User currentUser = (User) session.getAttribute("USER_SESSION");
    PageResult<Post> pageResult = (PageResult<Post>) request.getAttribute("pageResult");
    List<Category> categories = (List<Category>) request.getAttribute("categories");
    String keyword = (String) request.getAttribute("keyword");
    Integer categoryId = (Integer) request.getAttribute("categoryId");
%>

<div class="header">
    <div class="header-content">
        <div class="logo">💬 论坛首页</div>

        <div class="user-nav">
            <% if (currentUser != null) { %>
            <span style="color: #374151; font-weight: 500;">欢迎，<%= currentUser.getUsername() %>！</span>
            <a href="/user/profile" class="nav-secondary">👤 个人中心</a>
            <a href="/post" class="nav-primary">✏️ 发帖</a>
            <a href="/logout" class="nav-ghost">🚪 退出</a>
            <% } else { %>
            <a href="/login" class="nav-secondary">🔑 登录</a>
            <a href="/register" class="nav-primary">📝 注册</a>
            <% } %>
        </div>
    </div>
</div>

<div class="container">
    <div class="page-title">
        <h1>欢迎来到论坛</h1>
        <p style="color: #6b7280; font-size: 16px;">分享知识，交流想法，共同成长</p>
    </div>

    <!-- 改进的搜索表单 - 使用POST方式解决中文编码问题 -->
    <div class="search-section">
        <div class="search-header">
            <span>🔍</span>
            <h3>搜索与筛选</h3>
        </div>
        <div class="search-form">
            <form method="post" action="/main/search" accept-charset="UTF-8">
                <div class="form-row">
                    <div class="form-group">
                        <label>分类：</label>
                        <select name="categoryId">
                            <option value="">全部分类</option>
                            <% if (categories != null) {
                                for (Category cat : categories) { %>
                            <option value="<%= cat.getId() %>" <%= (categoryId != null && categoryId.equals(cat.getId())) ? "selected" : "" %>>
                                <%= cat.getName() %>
                            </option>
                            <% }
                            } %>
                        </select>
                    </div>

                    <div class="form-group" style="flex: 2;">
                        <label>关键词：</label>
                        <input type="text" name="keyword" value="<%= keyword != null ? keyword : "" %>" placeholder="搜索标题或内容...">
                    </div>

                    <div class="search-buttons">
                        <button type="submit" class="btn btn-primary">🔍 搜索</button>
                        <a href="/main" class="btn btn-outline">🗑️ 清除条件</a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-grid">
        <% if (pageResult != null && pageResult.getRows() != null && !pageResult.getRows().isEmpty()) { %>
        <% for (Post post : pageResult.getRows()) { %>
        <div class="post-item">
            <div class="post-content">
                <div class="post-header">
                    <div class="post-title">
                        <h3><a href="/postDetail?id=<%= post.getId() %>"><%= post.getTitle() %></a></h3>
                        <div class="post-meta">
                                <span class="meta-item">
                                    <span>👤</span>
                                    <span>作者：<%= post.getUsername() != null ? post.getUsername() : "用户" + post.getUserId() %></span>
                                </span>
                            <span class="meta-item">
                                    <span>🕒</span>
                                    <span>发布时间：<%= post.getCreateTime() %></span>
                                </span>
                        </div>
                    </div>
                </div>

                <div class="post-text">
                    <%= post.getContent().length() > 100 ? post.getContent().substring(0, 100) + "..." : post.getContent() %>
                </div>

                <div class="post-actions">
                    <div class="action-buttons">
                        <% if (currentUser != null) { %>
                        <button class="like-btn <%= (post.getIsLiked() != null && post.getIsLiked()) ? "liked" : "" %>"
                                onclick="togglePostLike(<%= post.getId() %>, this)">
                            <span>👍</span>
                            <span class="like-count"><%= post.getLikeCount() != null ? post.getLikeCount() : 0 %></span>
                        </button>
                        <% } else { %>
                        <span class="like-display">
                                <span>👍</span>
                                <span><%= post.getLikeCount() != null ? post.getLikeCount() : 0 %></span>
                            </span>
                        <% } %>

                        <a href="/postDetail?id=<%= post.getId() %>" class="action-link link-primary">
                            <span>👁️</span>
                            <span>查看详情</span>
                        </a>

                        <% if (currentUser != null && currentUser.getId().equals(post.getUserId())) { %>
                        <a href="/post/edit?id=<%= post.getId() %>" class="action-link link-success">
                            <span>✏️</span>
                            <span>编辑</span>
                        </a>
                        <% } %>
                    </div>
                </div>
            </div>
        </div>
        <% } %>

        <!-- 分页 - 改进URL编码处理 -->
        <div class="pagination-section">
            <div class="pagination">
                <%
                    int currentPage = pageResult.getPageNum();
                    int totalPages = pageResult.getTotalPages();
                    String baseUrl = "/main?pageSize=" + pageResult.getPageSize();
                    if (keyword != null && !keyword.trim().isEmpty()) {
                        try {
                            baseUrl += "&keyword=" + URLEncoder.encode(keyword, "UTF-8");
                        } catch (Exception e) {
                            baseUrl += "&keyword=" + keyword;
                        }
                    }
                    if (categoryId != null) baseUrl += "&categoryId=" + categoryId;
                %>

                <div class="pagination-buttons">
                    <% if (currentPage > 1) { %>
                    <a href="<%= baseUrl %>&pageNum=<%= currentPage - 1 %>" class="page-link">← 上一页</a>
                    <% } %>

                    <% for (int i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) { %>
                    <a href="<%= baseUrl %>&pageNum=<%= i %>"
                       class="page-link <%= i == currentPage ? "current" : "" %>"><%= i %></a>
                    <% } %>

                    <% if (currentPage < totalPages) { %>
                    <a href="<%= baseUrl %>&pageNum=<%= currentPage + 1 %>" class="page-link">下一页 →</a>
                    <% } %>
                </div>

                <div class="pagination-info">
                    第 <%= currentPage %> 页，共 <%= totalPages %> 页，总计 <%= pageResult.getTotalCount() %> 条记录
                </div>
            </div>
        </div>
        <% } else { %>
        <div class="empty-state">
            <div style="font-size: 48px; margin-bottom: 16px;">📝</div>
            <h3>暂无帖子数据</h3>
            <p>还没有人发布帖子，快来发布第一个帖子吧！</p>
        </div>
        <% } %>
    </div>
</div>

<script>
    // 帖子点赞功能
    function togglePostLike(postId, button) {
        fetch('/like/post', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: 'postId=' + postId
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新按钮状态
                    if (data.isLiked) {
                        button.classList.add('liked');
                    } else {
                        button.classList.remove('liked');
                    }

                    // 更新点赞数
                    const likeCountSpan = button.querySelector('.like-count');
                    likeCountSpan.textContent = data.likeCount;

                    // 显示提示信息
                    showMessage(data.message, 'success');
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('操作失败，请重试', 'error');
            });
    }

    // 显示提示信息 - 使用美化的动画效果
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        messageDiv.textContent = message;
        messageDiv.className = 'message-toast message-' + type;

        document.body.appendChild(messageDiv);

        // 显示动画
        setTimeout(() => {
            messageDiv.classList.add('show');
        }, 100);

        // 3秒后移除
        setTimeout(() => {
            messageDiv.classList.remove('show');
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    document.body.removeChild(messageDiv);
                }
            }, 300);
        }, 3000);
    }
</script>

</body>
</html>
